package com.itheima.reggie.controller;

import cn.hutool.core.io.IoUtil;
import com.itheima.reggie.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

@RestController
@RequestMapping("/common")
public class CommonController {

    /**
     * 图片上传功能
     */
    @Value("${reggie.file-path}")
    private String path;

    @PostMapping("/upload")
    public R upload(MultipartFile file) {
        String fileName = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
        //重新获取文件名
        fileName = fileName + substring;
        try {
            file.transferTo(new File(path +File.separator+ fileName));
            return R.success(fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return R.error("上传图片失败");
        }
    }

    /**
     * 图片下载功能
     */
    @GetMapping("/download")
    public void download(String name , HttpServletResponse response) throws Exception {
        //读取磁盘中的文件(io流)
        response.setHeader("Content-Disposition","attachment; filename="+new String(name.getBytes(),"ISO-8859-1"));
        FileInputStream fileInputStream = new FileInputStream(path + File.separator+ name);
        IoUtil.copy(fileInputStream,response.getOutputStream());
        //释放资源
        fileInputStream.close();
    }
}
